/**
 * Created by Kpeng on 2017/7/3.
 * Depending on the jquery-1.12.4.min.js.
 * Depending on the common.js.
 * Depending on the style.min.css.
 * To cite this document, always state the source as shown above.
 * -------------------------------
 * Module:员工管理
 * -------------------------------
 */

$(function () {
  wzERP.Staff.init();
});

wzERP.Staff.init = function () {
  wzERP.Common.inlineDate('#rangestart', '#rangeend');
  wzERP.Staff.addHandle(); //添加员工
  wzERP.Staff.viewHandle(); //查看员工
  wzERP.Staff.editHandle(); //编辑员工
  wzERP.Staff.delHandle(); //删除员工
  wzERP.Staff.turnPage();//分页
  //wzERP.Staff.selectDepart();
};

//添加员工
wzERP.Staff.addHandle = function () {
  var opt = {
    ele: '.addBtn',
    modalBox: '#modal',
    modalTitleStr: '添加员工',
    onApprove: function () {
      if (!!wzERP.Staff.checkform('#addEmployee')) {
        layer.msg('填写项不符合规则', {icon: 2});
        return false;
      }
      //兼岗批量传输
      var receiveArray = [];
      var $Array = $('#addEmployee').find('.subpost-list .subpost-item');
      $Array.each(function () {
        var $code = $(this).find('input[name="cmp"]');
        var $depart = $(this).find('input[name="depart"]');
        var $job = $(this).find('input[name="job"]');
        receiveArray.push({
          'partCompanyCode': $code.val(),
          'partDepartmentId': $depart.val(),
          'partPositionId': $job.val()
        })
      })
      var formObj = formSerializeToObj('#addEmployee');
      formObj['partPositionListVos'] = receiveArray;

      $.ajax({
        type: "POST",
        url: '/basedata/employee/add',
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(formObj),
        success: function (data) {
          switch (data.code) {
            case 0://成功
              layer.msg(data.msg, {icon: 7});
              break;
            case 1: //失败
              layer.msg(data.msg, {icon: 5});
              break;
            default: //默认
              layer.msg(data.msg, {icon: 2});
          }
          wzERP.Common.delayReload(wzERP.delayTime);
        }
      });
    },
    snippets: $("#addemployeeHtml").val()
  };

  wzERP.Common.handleData(opt);
};

//查看员工
wzERP.Staff.viewHandle = function () {
  var opt = {
    ele: '.viewBtn',
    modalTitleStr: '员工详情',
    modalBox: '#modal',
    onApprove: function () {
    },
    snippets: $("#employeeFindHtml").val()
  };
  wzERP.Common.handleData(opt);
};

//表单验证出口
wzERP.Staff.checkform = function (ele) {
  /*Arg Guide
   @ ele 要验证的表单
   */
  $(ele).form('submit');
  return $(ele).hasClass('error');
}

//编辑员工
wzERP.Staff.editHandle = function () {
  var opt = {
    ele: '.editBtn',
    modalBox: '#modal',
    modalTitleStr: '编辑员工信息',
    onApprove: function () {
      if (!!wzERP.Staff.checkform('#addEmployee')) {
        layer.msg('填写项不符合规则', {icon: 2});
        return false;
      }
      //获取员工id
      var id = $('#modal').find('.setId').data('id');
      ///兼岗批量传输
      var receiveArray = [];
      var $Array = $('#addEmployee').find('.subpost-list .subpost-item');
      $Array.each(function () {
        var $code = $(this).find('input[name="cmp"]');
        var $depart = $(this).find('input[name="depart"]');
        var $job = $(this).find('input[name="job"]');
        receiveArray.push({
          'partCompanyCode': $code.val(),
          'partDepartmentId': $depart.val(),
          'partPositionId': $job.val()
        })
      })
      var formObj = formSerializeToObj('#addEmployee');
      formObj['partPositionListVos'] = receiveArray;
      formObj['employeeId'] = id;

      $.ajax({
        type: "POST",
        url: '/basedata/employee/update',
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(formObj),
        success: function (data) {
          switch (data.code) {
            case 0://成功
              layer.msg(data.msg, {icon: 7});
              break;
            case 1: //失败
              layer.msg(data.msg, {icon: 5});
              break;
            default: //默认
              layer.msg(data.msg, {icon: 2});
          }
          wzERP.Common.delayReload(wzERP.delayTime);
        }
      });
    },
    snippets: $("#employeeUpdateHtml").val()
  };
  wzERP.Common.handleData(opt);
};

//删除员工
wzERP.Staff.delHandle = function () {
  /*var opt = {
   ele: '.delBtn',
   modalBox: '#modal',
   modalTitleStr: '',
   onApprove: function () {
   wzERP.Common.deleteData('#delEmployeeUrl', $(this).find('.setId'));
   },
   snippets: $("#employeeDeleteHtml").val()
   };
   wzERP.Common.handleData(opt);*/

  $('#main').on('click', '.delBtn', function () {
    var $self = $(this);
    layer.alert('确定删除该员工信息吗？', {
          title: '提示信息',
          btn: ['取消', '确认'],
          btn1: function (index) {
            layer.close(index)
          },
          btn2: function () {
            wzERP.Common.deleteData('#delEmployeeUrl', $self)
          }
        }
    );
  })
};

//分页跳转
wzERP.Staff.turnPage = function () {
  var opt = {
    pageUrl: $("#employeePageUrl").val(),
    pageSearch: "#searchForm",
    pagesTotal: parseInt($('#pages').val()),
    pageCurr: parseInt($('#current').val()),
    pageSize: parseInt($('#pageSize').val()),
    currId: "#current"
  };
  wzERP.Common.pagingHandle(opt);
};

//
function search() {
  $("#current").val(1);
  $("#searchForm").action = "/basedata/employee/queryByPage";
  $("#searchForm").submit();
}

//根据员工生日自动计算年龄
wzERP.Staff.countAge = function () {
  var d = new Date(),
      curYear = d.getFullYear();
  $('#birthday').calendar({
    type: 'date',
    today: true,
    formatter: {
      date: wzERP.Common.calendarFormatter
    },
    onChange: function (value) {
      $('#age').text(curYear - value.getFullYear()).show().css(
          {fontSize: "12px"});
      var ages = curYear - value.getFullYear();
      $('#age1').val(ages);
    }
  });
};

//添加兼岗
wzERP.Staff.addPostHanlde = function () {
  var subpostWrap = $('.subpost-wrap'),//外围
      subpostBox = subpostWrap.find('.subpost-box'), //
      subpostList = subpostWrap.find('.subpost-list'),
      subpostItem = subpostList.find('.subpost-item'), //所有已存在项
      selects = subpostBox.find('select'),
      isDiff = false,
      names = ["cmp", "depart", "job"]; //初始化name

  subpostItem.length ? subpostList.show() : subpostList.hide();

  //将已选的data-name赋到select上
  subpostBox.on('change', 'select', function () {
    var thisDataName = $(this).find('option:selected').data('name');
    $(this).data('name', thisDataName);
  });

  //呼出操作
  subpostWrap.on('click', '.add-subpost-btn', function () {
    subpostBox.show()
  })

  //添加操作
  subpostWrap.on('click', '.saveSubpostBtn', function () {
    var thisValArr = [],
        thisNameArr = [],
        subPostName = '',
        subPostVal = [],
        isFlag = true;
    subpostItem = subpostList.find('.subpost-item'); //所有已存在项

    selects.each(function (i) {  //遍历三个下拉框
      var thisVal = this.value,
          thisName = $(this).data('name');
      if (thisVal && thisName) {  //判断是否有值和名称
        thisValArr.push(thisVal);
        thisNameArr.push(thisName);
        subPostVal += '<input type="hidden" name=' + names[i] + ' value='
            + thisVal + ' class="val"/>';
      }
    });

    if (thisNameArr.length === names.length) {  //判断是否选了三个
      subPostName = thisNameArr.join('-');
    } else {
      isFlag = false;
      layer.msg("请选择完整", {icon: 7})
      return false;
    }

    if (subpostItem.length) {
      var thatValArr = [];
      subpostItem.each(function () {
        var hideVals = $(this).find('.val');  //存在项的每一组值
        hideVals.each(function () {
          thatValArr.push(this.value);
          if (thatValArr.length === hideVals.length) {
            isDiff = wzERP.Common.isSame(thisValArr, thatValArr);
            if (isDiff === 0) {
              layer.msg("该职位已存在", {icon: 7})
              isFlag = false;
              return false;
            } else {
              isFlag = true;
              thatValArr = [];
            }
          }
        });
      });
    }
    if (isFlag) {
      var temp = '<section class="subpost-item"><p><span>' + subPostName
          + '</span><button type="button" class="delSubpostBtn"><i class="minus red square icon"></i></button></p>'
          + subPostVal + '</section>'
      subpostList.append(temp).show();
      subpostBox.find(".cancelSubpostBtn").trigger('click');
      //ajax添加兼岗
      // $.post('/basedata/partTimePosition/add',{employeeId:companyId,positionId:positionId},function (result) {
      //     console.log(result)
      // })
    }
  });

  //移除岗位
  subpostList.on('click', '.delSubpostBtn', function () {
    $(this).parents('.subpost-item').remove();
    subpostItem = subpostList.find('.subpost-item'); //所有已存在项
    if (subpostItem.length === 0) {
      $('.subpost-list').hide();
    }
  });

  //取消操作
  subpostWrap.on('click', '.cancelSubpostBtn', function () {
    //清空值并隐藏
    subpostBox.hide().find('select').each(function () {
      $(this).val('')
    })
  });
};

//表单验证器
wzERP.Staff.verifier = function (_selector) {
  /*Arg Guide
   @_selector: 对象选择器
   */
  $(_selector).form({
    on: 'blur',
    // inline: true,
    transition: 'fade',
    fields: {
      //员工卡号
      staffCardNo: {
        identifier: 'cardNo',
        rules: [{
          type: 'empty',
          prompt: '请输打卡号'
        },
          {
            type: 'regExp[/^([0-9]+(;|；)?)+$/]',
            prompt: '请输入正确的格式'
          },
          {
            type: 'regExp[/^.{0,20}$/]',
            prompt: '限制20字'
          }]
      },
      //员工QQ密码
      staffQQPassword: {
        identifier: 'qqPassword',
        rules: [{
          type: 'empty',
          prompt: '请输入QQ密码'
        },
          {
            type: 'regExp[/^.{0,20}$/]',
            prompt: '限制20字'
          }]
      },
      //员工姓名
      staffName: {
        identifier: 'employeeName',
        rules: [{
          type: 'empty',
          prompt: '请输入姓名'
        },
          {
            type: 'regExp[/^.{0,20}$/]',
            prompt: '限制20字'
          }]
      },
      //员工入职时间
      staffEntryDate: {
        identifier: 'entryDate',
        rules: [{
          type: 'empty',
          prompt: '请输入职日期'
        }]
      },
      //员工性别
      staffGender: {
        identifier: 'gender',
        rules: [{
          type: 'empty',
          prompt: '请输性别'
        }]
      },
      //员工工作QQ
      staffQQ: {
        identifier: 'workQq',
        rules: [{
          type: 'empty',
          prompt: '请输工作QQ'
        },
          {
            type: 'regExp[/^[1-9]\\d{4,11}$/]',
            prompt: '请输入正确的格式'
          }]
      },
      //员工公司
      staffCompany: {
        identifier: 'companyId',
        rules: [{
          type: 'empty',
          prompt: '请选择公司'
        }]
      },
      //员工邮箱
      staffEmail: {
        identifier: 'email',
        optional: true,
        rules: [{
          type: 'regExp[/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/]',
          prompt: '请输入正确的格式'
        },
          {
            type: 'regExp[/^.{0,30}$/]',
            prompt: '限制30字'
          }]
      },
      //员工部门
      staffDepartment: {
        identifier: 'departmentId',
        rules: [{
          type: 'empty',
          prompt: '请选择部门'
        }]
      },
      //员工微信
      staffWechat: {
        identifier: 'weixin',
        rules: [{
          type: 'regExp[/^.{0,20}$/]',
          prompt: '限制20字'
        }]
      },
      //员工岗位
      staffPosition: {
        identifier: 'positionId',
        rules: [{
          type: 'empty',
          prompt: '请选择岗位'
        }]
      },
      //员工职称
      staffProfession: {
        identifier: 'professionId',
        rules: [{
          type: 'empty',
          prompt: '请选择职称'
        }]
      },
      //员工手机
      staffPhone: {
        identifier: 'phone',
        rules: [{
          type: 'empty',
          prompt: '请输入联系电话'
        },
          {
            type: 'regExp[/^(0|86|17951)?(13[0-9]|15[012356789]|17[035678]|18[0-9]|14[57])[0-9]{8}$/]',
            prompt: '请输入正确的格式'
          }]
      },
      //员工公农历
      staffGongLi: {
        identifier: 'gongLiFlag',
        rules: [{
          type: 'empty',
          prompt: '请选择公农历'
        }]
      },
      //员工生日
      birthDate: {
        identifier: 'birthDate',
        rules: [{
          type: 'empty',
          prompt: '请选择生日'
        }]
      },
      //员工昵称
      staffNickname: {
        identifier: 'nickname',
        rules: [
          {
            type: 'regExp[/^.{0,20}$/]',
            prompt: '限制20字'
          }]
      }
    }
  });

};

//序列化表单值转为对象
function formSerializeToObj(id) {
  /*Arg Guide
   @ id 表单id
   */
  // 获取表单序列值
  var content;
  if (typeof id == 'string' && id[0] == '.') {
    content = $(id).serialize();
  } else if (typeof id == 'string' && id[0] == '#') {
    content = $(id).serialize();
  } else {
    content = $("#" + id).serialize();
  }
  content = decodeURIComponent(content, true);
  //使用方法分割取出
  var contentS = content.split('&')
  var obj = {}
  for (var i = 0; i < contentS.length; i++) {
    var con = contentS[i].toString()
    var son = con.split('=')
    obj[son[0]] = son[1]
  }
  return obj
}

